﻿package com.projects.xenia.documents_activities;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.projects.xenia.Documents_Location;
import com.projects.xenia.MainCommentsActivity;
import com.projects.xenia.MainCustomersListActivity;
import com.projects.xenia.MainGoodsCatalogActivity;
import com.projects.xenia.R;
import com.projects.xenia.add_activities.Activity_InfoTabs;
import com.projects.xenia.documents_classes.Documents_Order;
import com.projects.xenia.documents_classes.Documents_Visit;
import com.projects.xenia.global_modules.MainGlobalModule;



import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


public class Activity_Order extends Activity  {

	private final Context Ctx = this;
	
	private Documents_Order DocumentClass;
	
	private final int IDD_OrderDateDialog = 0;
	private final int IDD_OrderExecuteDateDialog = 1;	
	private final int IDD_OrderAccTypeDialog = 2;
	private final int IDD_OrderFirmDialog = 3;
	private final int IDD_OrderDepartmentDialog = 4;	
	
	private final int IDR_CustomerSelect = 0;
	private final int IDR_GoodsSelect = 1;
	private final int IDR_CommentsSelect = 2;
	private final int IDR_GPSSettingsTest = 3;
	private final int IDR_MobileNetworkSettingsTest = 4;
	private final int IDR_OrderListOpen = 5;
	
	private ImageView OrderGpsState;
	
	private ImageView ord_back;
	private ImageView ord_docgoodsopen;
	private ImageView ord_goodsopen;
	
	private ImageView iv_info;
	
	
	private Button OrderDate;
	private Button OrderExecuteDate;
	
	private Button OrderCustomer;	
	
	private Button OrderAccType;
	private Button OrderFirm;
	private Button OrderDepartment;	
	private Button OrderComments;
	
	private Cursor OrderAccTypeCursor; 
	private Cursor OrderFirmCursor; 
	private Cursor OrderDepartmentCursor;
	
	private TextView OrderTotalOrderSum;
	
	private TextView OrderTotalRestSum;
	
	
	@Override
	protected void onDestroy() {		
		super.onDestroy();		
		MainGlobalModule.Documents_Location.StopLocation();
		MainGlobalModule.Documents_Location = null;
		MainGlobalModule.DocumentClass = null;		
	}
	
	protected Cursor GetCursorByTable (String DB_TABLE) {
			return (MainGlobalModule.DBE.rawQuery("select id as _id, descr as descr from "+DB_TABLE+" order by descr", null));		
	}		
	
	@Override
	public Object onRetainNonConfigurationInstance() {
		return (DocumentClass);		
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		if (!MainGlobalModule.CheckGPSSettings(false)) {			
			startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),IDR_GPSSettingsTest);
		}
		
		if (!MainGlobalModule.CheckMobileNetworkSettings()) {			
			startActivityForResult(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS),IDR_MobileNetworkSettingsTest);
		}
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);            
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		setContentView(R.layout.order_main_form);
		
		Bundle DocExtras;
		DocExtras = getIntent().getExtras();
		
		DocumentClass = (Documents_Order) getLastNonConfigurationInstance();
		
		if (DocumentClass== null) {			
			DocumentClass = new Documents_Order ();			
			if (DocExtras!=null) {
				if (DocExtras.getString("DocId")!=null) {
					DocumentClass.OpenDoc(DocExtras.getString("DocId"));					
					}
				else {
					DocumentClass.NewDoc();
					DocumentClass.Head.customers_id = DocExtras.getString("CustomerId");
					}			
			}	
			else {
				DocumentClass.NewDoc();
			}			
		}		
		
		MainGlobalModule.DocumentClass = DocumentClass;	
		
		if (MainGlobalModule.SettingsCollection.get("ManagerId").equals("")) {
			Toast.makeText(this, "Устройство не авторизовано !!!", Toast.LENGTH_SHORT).show();
			if (DocumentClass.Head.state==0 ) {
				DocumentClass.Head.customers_id = null;	
			}
			FinishActivity();
		}		
		
		OrderGpsState = (ImageView) findViewById(R.id.OrderGpsState);
		OrderGpsState.setVisibility(View.INVISIBLE);
		
		if (MainGlobalModule.Documents_Location==null) {
			MainGlobalModule.Documents_Location = new Documents_Location();
			MainGlobalModule.Documents_Location.StartLocation(this, MainGlobalModule.DocumentsType.Order, DocumentClass.Head.id,OrderGpsState);
		}		
		
		OrderDate = (Button) findViewById(R.id.OrderDate);
		//OrderDate.setOnClickListener(OrderDateDialog);
		RefreshDate (OrderDate,DocumentClass.Head.date_create);		
		
		OrderExecuteDate = (Button) findViewById(R.id.OrderExecuteDate);
		OrderExecuteDate.setOnClickListener(OrderExecuteDateDialog);
		RefreshDate (OrderExecuteDate,DocumentClass.Head.date_execute);
		
		OrderCustomer = (Button) findViewById(R.id.OrderCustomer);
		OrderCustomer.setOnClickListener(OrderCustomerSelect);
		OrderCustomer.setOnLongClickListener(CustomerLongSelect);
		RefreshByCursor (OrderCustomer , "xref_customers", DocumentClass.Head.customers_id);	
		
		OrderAccTypeCursor = GetCursorByTable ("xenum_AccType");
		OrderAccType = (Button) findViewById(R.id.OrderAccType);
		OrderAccType.setOnClickListener(OrderAccTypeDialog);
		RefreshByCursor (OrderAccType , "xenum_acctype", DocumentClass.Head.acctype);
		
		OrderFirmCursor = GetCursorByTable ("xref_firms");
		OrderFirm = (Button) findViewById(R.id.OrderFirm);
		OrderFirm.setOnClickListener(OrderFirmDialog);
		RefreshByCursor (OrderFirm , "xref_firms", DocumentClass.Head.firms_id);
		
		OrderDepartmentCursor = GetCursorByTable ("xref_departments");
		OrderDepartment = (Button) findViewById(R.id.OrderDepartment);
		OrderDepartment.setOnClickListener(OrderDepartmentDialog);
		RefreshByCursor (OrderDepartment , "xref_departments", DocumentClass.Head.departments_id);
		
		OrderTotalOrderSum = (TextView) findViewById(R.id.OrderTotalOrderSum);		
		RefreshByDecimalValue (OrderTotalOrderSum,DocumentClass.Head.total_ordersum);
		
		OrderTotalRestSum = (TextView) findViewById(R.id.OrderTotalRestSum);		
		RefreshByDecimalValue (OrderTotalRestSum,DocumentClass.Head.total_restsum);
		
		OrderComments = (Button) findViewById(R.id.OrderCommentsButton);
		OrderComments.setOnClickListener(OrderCommentsButton_Click);		
		
		RefreshMultipleByCursor (OrderComments,"xdoc_Orders_D");		
		
		iv_info = (ImageView)findViewById(R.id.iv_info);
		iv_info.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				OpenCustomerInfo ();
			}
		});
		
		ord_back = (ImageView)findViewById(R.id.BackwardButton);
		ord_back.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {				
				CloseDocument ();	
			}
		});
		
		ord_docgoodsopen = (ImageView)findViewById(R.id.contentopen);
		ord_docgoodsopen.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				OpenDocumentsGoods();	
			}
		});
		
		ord_goodsopen = (ImageView)findViewById(R.id.goodsopen);		
		ord_goodsopen.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				OpenGoodsCatalog (false);				
			}
		});
		
		
		GetCustomersAddData ();
		
	}
 
	
	private void AgreesControl () {
		
		if (Boolean.parseBoolean(MainGlobalModule.ConstantsCollection.get("ControlAgrees")) ) {		
		
			String AlertString = null;
		
			Cursor Agrees = MainGlobalModule.DBE.rawQuery("select number, date (datebegin) , date (dateend) from xref_CustomersAgreements where customers_id = ?", new String [] {DocumentClass.Head.customers_id});
			if (Agrees==null || Agrees.getCount()<1) {
				AlertString =  "У клиента нет договора";
			}
			else {
				Agrees = MainGlobalModule.DBE.rawQuery("select number, date (datebegin) , date (dateend) from xref_CustomersAgreements where customers_id = ? and date (dateend) < date('now') ", new String [] {DocumentClass.Head.customers_id});
				if (Agrees!=null && Agrees.getCount()>0) {
					AlertString =  "У клиента просрочен договор";
				}
			}
		
			if  (AlertString!=null) {			
				AlertDialog.Builder adb = new AlertDialog.Builder (Ctx);
				adb.setIcon(android.R.drawable.ic_dialog_alert);
				adb.setMessage(AlertString);
				adb.setTitle("Договор");
				adb.setPositiveButton("OK", null);
				adb.create().show();
			}
		
		}
	}
	
	private void DebetsControl () {
	
		if (Boolean.parseBoolean(MainGlobalModule.ConstantsCollection.get("ControlDebts")) ) {
			
			int maximumrest = Integer.parseInt(MainGlobalModule.ConstantsCollection.get("ControlDebtsLock"));			
			
			Cursor DebtsDetailsCursor = MainGlobalModule.DBE.rawQuery ("select distinct d.docid, d.docdate, d.docnum, t.descr , d.docpaydate, d.totalsum, d.restsum, julianday(date(d.docpaydate))-julianday(date(d.docdate)), julianday(date(d.docpaydate))-julianday(date('now')), d.doctype, a.descr from xref_debts d left outer join xenum_typedoc t on d.doctype = t.id  left outer join xenum_AccType a on d.acctype = a.id where d.customers_id=? order by d.docdate asc",new String [] {DocumentClass.Head.customers_id});
			
			if (DebtsDetailsCursor!=null && DebtsDetailsCursor.getCount()>0) {
				
				DebtsDetailsCursor.moveToFirst();
				
				while (!DebtsDetailsCursor.isAfterLast()) {
				
					String datedoc = MainGlobalModule.FormatDate(MainGlobalModule.SqlStringToDate(DebtsDetailsCursor.getString(1)));   
					String docnumber = DebtsDetailsCursor.getString(2);			
					String doctype = DebtsDetailsCursor.getString(3);
					double docsumm = DebtsDetailsCursor.getDouble(5);			
					double docrestsumm = DebtsDetailsCursor.getDouble(6);
					double docpaydatecout = DebtsDetailsCursor.getDouble(7);
					double docpaydaterest = DebtsDetailsCursor.getDouble(8);				
					
					
					if (docpaydaterest<0) {
						
						docpaydaterest = -docpaydaterest;
						
						AlertDialog.Builder adb = new AlertDialog.Builder (Ctx);						
						adb.setIcon(android.R.drawable.ic_dialog_alert);
						adb.setMessage(String.format("Есть просроченный документ%n№%s от %s %nна сумму %.2f%nостаток задолженности %.2f%nпросрочка %.0f дн.", docnumber,datedoc,docsumm,docrestsumm,docpaydaterest));
						adb.setTitle("Просрочка");
						adb.setPositiveButton("Продожить", null);
						
						if  (docpaydaterest>maximumrest) {
							adb.setPositiveButton("Закрыть", new AlertDialog.OnClickListener() {								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									if (DocumentClass.BackupIsExists()) {
							    		DocumentClass.RestoreDocument();
							    		finish();
							    	}
							    	else {
							    		DocumentClass.Head.customers_id = null;
							    		FinishActivity ();
							    	}		
								}								
							});
						}
						
						adb.create().show();
						
						break;
						
					}
					
					DebtsDetailsCursor.moveToNext();
					
				}

					
			}
			
				
		}	
		
	}
	
	private void CategoryControl () {
	
		boolean warning = false;
		boolean blocking = false;
		
		StringBuilder DestString = new StringBuilder();
		
		
		String [] ControlCategories = MainGlobalModule.ConstantsCollection.get("ControlCategories").split(",");
		String [] BlockingCategories = MainGlobalModule.ConstantsCollection.get("ControlCategoriesLock").split(",");
		
		if (ControlCategories.length>0 | BlockingCategories.length>0) {			
		
			Cursor ControlCategory = MainGlobalModule.DBE.rawQuery("select b.id, b.descr from xref_CustomersCategory a inner join xref_Category b on a.category_id = b.id where a.customers_id = ?", new String [] {DocumentClass.Head.customers_id});		
			
			if (ControlCategory!=null & ControlCategory.getCount()>0) {				
						
				List <String> cc = Arrays.asList(ControlCategories);
				List <String> bc = Arrays.asList(BlockingCategories);
				
				ControlCategory.moveToNext();
				
				while (!ControlCategory.isAfterLast()) {
					
					String _id = ControlCategory.getString(0); 
					String _descr = ControlCategory.getString(1);
					
					if (cc.contains(_id)) {
						warning = true;
						DestString.append(_descr);
						DestString.append("%n");						
					}
					
					if (bc.contains(_id)) {
						blocking = true;
						DestString.append(_descr);
						DestString.append("%n");						
					}

					ControlCategory.moveToNext();
					
				}
				
			}
			
		}
		
		if (warning | blocking) {
			
			AlertDialog.Builder adb = new AlertDialog.Builder (Ctx);						
			adb.setIcon(android.R.drawable.ic_dialog_alert);
			adb.setMessage(String.format("Внимание!%nклиент принадлежит к категориям:%n".concat(DestString.toString()).concat(blocking?"%nи заблокирован!":"")));			
			adb.setTitle("Категории");
			
			if (blocking) {
				adb.setPositiveButton("Закрыть", new AlertDialog.OnClickListener() {								
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (DocumentClass.BackupIsExists()) {
				    		DocumentClass.RestoreDocument();
				    		finish();
				    	}
				    	else {
				    		DocumentClass.Head.customers_id = null;
				    		FinishActivity ();
				    	}		
					}								
				});
			}
			else {
				adb.setPositiveButton("Продожить", null);
			}
			
			adb.create().show();
		}
		
	}
	
	private void GetCustomersAddData () {
		
		if (DocumentClass.Head.customers_id!=null) {
			
			AgreesControl ();
			DebetsControl ();
			CategoryControl ();
			
			DocumentClass.GetLastSales();			
			DocumentClass.GetAssortment();
			DocumentClass.GetCustomerAssortment();
		}		
		
	}
	
	
	private void OpenCustomerInfo () {
		
		if (DocumentClass.Head.customers_id != null) {
			
			Intent InfoTabs = new Intent ();
			InfoTabs.setClass(Ctx,Activity_InfoTabs.class);
		
			InfoTabs.putExtra("customer_id", DocumentClass.Head.customers_id);
			InfoTabs.putExtra("dayofroute",0);
			InfoTabs.putExtra("journaltab", false);
			startActivity(InfoTabs);
			
		}
	
	}
	
	private OnLongClickListener CustomerLongSelect = new OnLongClickListener() {		
		@Override
		public boolean onLongClick(View v) {
			OpenCustomerInfo ();
			return true;
		}
	};
	
	private OnClickListener OrderCommentsButton_Click = new OnClickListener() {		
		@Override
		public void onClick(View v) {
					
			Intent Comments = new Intent();
			Comments.setClass(Ctx,MainCommentsActivity.class);
			Comments.putExtra("DocId",  DocumentClass.Head.id);
			Comments.putExtra("Destination_Table",  "xdoc_Orders_D");
			Comments.putExtra("Source_Table",  "xenum_OrderNotes");
			startActivityForResult(Comments, IDR_CommentsSelect);			
			
		}
	};
	
	private void RefreshByDecimalValue (TextView DecimalTextView, Double DecimalValue) {
		
		DecimalTextView.setText(String.format("%.2f", DecimalValue));
		
	}
	
	private OnClickListener OrderCustomerSelect= new OnClickListener () {	
		
		@Override
		public void onClick(View v) {
			
			Documents_Visit DocVisit = new Documents_Visit ();			 
			if (DocVisit.CheckOpenVisitsExistsByCustomerId(DocumentClass.Head.customers_id)) {
				Toast.makeText(Ctx, "Нельзя изменить клиента если есть открытый визит !", Toast.LENGTH_LONG).show();
			}
			else {
				Intent CustomerSelectintent = new Intent();
				CustomerSelectintent.setClass(Ctx,MainCustomersListActivity.class);
				CustomerSelectintent.putExtra("customer_id", DocumentClass.Head.customers_id);
				CustomerSelectintent.putExtra("customer_descr","");
	            startActivityForResult (CustomerSelectintent,IDR_CustomerSelect);	
			}
            
		}
		
	};
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {	
				 
		 switch(requestCode) {
		 
		    case IDR_CustomerSelect:
		    	if (resultCode==RESULT_OK) {
		    		OrderCustomer.setText(data.getStringExtra("customer_descr"));
		    		DocumentClass.Head.state = 1;
		    		DocumentClass.Head.customers_id = data.getStringExtra("customer_id");
		    		DocumentClass.UpdateDoc();
		    		RefreshByCursor(OrderCustomer, "xref_customers", DocumentClass.Head.customers_id);
		    		GetCustomersAddData ();
		    	}
		    	break;
		    	
		    case IDR_GoodsSelect:		    	
		    	RefreshByDecimalValue (OrderTotalOrderSum, DocumentClass.Head.total_ordersum);
		    	RefreshByDecimalValue (OrderTotalRestSum, DocumentClass.Head.total_restsum);
		    	break;
		    	
		    case IDR_CommentsSelect:
		    	DocumentClass.Head.state = 1;
		    	RefreshMultipleByCursor (OrderComments,"xdoc_Orders_D");
		    	break;
		    	
		    case IDR_GPSSettingsTest:		    	
		    	if (!MainGlobalModule.CheckGPSSettings(false)) {			
		    		startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),IDR_GPSSettingsTest);
		    	}
		    	break;
		    	
		    case IDR_MobileNetworkSettingsTest:
		    	if (!MainGlobalModule.CheckMobileNetworkSettings()) {
		    		startActivityForResult(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS),IDR_MobileNetworkSettingsTest);
		    	}
		    	break;
		    	
		    case IDR_OrderListOpen:		    	
		    	RefreshByDecimalValue (OrderTotalOrderSum, DocumentClass.Head.total_ordersum);
		    	RefreshByDecimalValue (OrderTotalRestSum, DocumentClass.Head.total_restsum);		    	
		    	break;
		    	
		 }		 
		    	
	};		
	
	private void RefreshDate (Button DateButton,Date DateValue) {
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
		DateButton.setText(sdf.format(DateValue));
	}	
	
	private void RefreshByCursor (Button SelectButton, String Table, String Id) {
		
		try {
			Cursor ScalarCursor = MainGlobalModule.DBE.query (Table, new String []{"descr"}, "id = ?", new String []{Id}, null, null, null);
			ScalarCursor.moveToFirst();
			SelectButton.setText(ScalarCursor.getString(0));
		} catch (Exception e) {
			SelectButton.setText ("");
		}		
	}
	
	private void RefreshMultipleByCursor (Button SelectButton, String Table) {
		
		String StringValues = "";
		try {
			Cursor ScalarCursor = MainGlobalModule.DBE.query (Table, new String []{"descr"}, "hdoc_id = ?", new String []{DocumentClass.Head.id},null,null,null);
			//ScalarCursor.moveToFirst();
			//StringValues.concat(ScalarCursor.getString(0));
			while (ScalarCursor.moveToNext()){
				StringValues = StringValues.concat(ScalarCursor.getString(0))+","; 
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		SelectButton.setText(StringValues);
		
	}
	
	private OnClickListener OrderDateDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			showDialog(IDD_OrderDateDialog);			
		}
	};

	private OnClickListener OrderExecuteDateDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			showDialog(IDD_OrderExecuteDateDialog);			
		}
	};
	
	private OnClickListener OrderAccTypeDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			showDialog(IDD_OrderAccTypeDialog);			
		}
	};
	
	private OnClickListener OrderFirmDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			showDialog(IDD_OrderFirmDialog);			
		}
	};

	private OnClickListener OrderDepartmentDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			showDialog(IDD_OrderDepartmentDialog);			
		}
	};
	
	@Override
	protected Dialog onCreateDialog(int id) {		
			
			super.onCreateDialog(id);
			
			int mYear;
			int mMonth;
			int mDay;
			
			Calendar C = Calendar.getInstance();
			
			AlertDialog.Builder adb = new AlertDialog.Builder(this);
			
			switch (id) {
			
			case IDD_OrderDateDialog:
				C.setTime(DocumentClass.Head.date_create);
				mYear = C.get(Calendar.YEAR);
				mMonth = C.get(Calendar.MONTH);
				mDay = C.get(Calendar.DAY_OF_MONTH);			
				return new DatePickerDialog(this, OrderDateSetListener, mYear, mMonth, mDay);
				
			case IDD_OrderExecuteDateDialog:
				C.setTime(DocumentClass.Head.date_execute);
				mYear = C.get(Calendar.YEAR);
				mMonth = C.get(Calendar.MONTH);
				mDay = C.get(Calendar.DAY_OF_MONTH);			
				return new DatePickerDialog(this, OrderExecuteDateSetListener, mYear, mMonth, mDay);

			case IDD_OrderAccTypeDialog:
				adb.setTitle("Типы Учета");
				adb.setCursor(OrderAccTypeCursor, OrderAccTypeDialogClickListener , "descr");
				return adb.create();
				
			case IDD_OrderFirmDialog:
					adb.setTitle("Фирмы");
					adb.setCursor(OrderFirmCursor, OrderFirmDialogClickListener , "descr");
					return adb.create();
			
			case IDD_OrderDepartmentDialog:	
					adb.setTitle("Склады");
					adb.setCursor(OrderDepartmentCursor, OrderDepartmentDialogClickListener , "descr");
					return adb.create();
					
			}
			
			return null;
			
		};
				
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
		
		int mYear;
		int mMonth;
		int mDay;
		Calendar C = Calendar.getInstance();
		DatePickerDialog M;
		
		switch (id) {
		
		case IDD_OrderDateDialog:		
			M = (DatePickerDialog)dialog;						
			C.setTime(DocumentClass.Head.date_create);		
			mYear = C.get(Calendar.YEAR);
			mMonth = C.get(Calendar.MONTH);
			mDay = C.get(Calendar.DAY_OF_MONTH);						
			M.updateDate(mYear, mMonth, mDay);
			break;
		case IDD_OrderExecuteDateDialog:		
			M = (DatePickerDialog)dialog;
			C.setTime(DocumentClass.Head.date_execute);		
			mYear = C.get(Calendar.YEAR);
			mMonth = C.get(Calendar.MONTH);
			mDay = C.get(Calendar.DAY_OF_MONTH);						
			M.updateDate(mYear, mMonth, mDay);
			break;			
			
		}		
		
	}
	
	private OnDateSetListener OrderDateSetListener = new OnDateSetListener() {		
		@Override
		public void onDateSet(DatePicker view, int year, int month,int day) {						
			Calendar C = Calendar.getInstance();
			C.set(year, month, day);
			DocumentClass.Head.state = 1;
			DocumentClass.Head.date_create = C.getTime();
			RefreshDate (OrderDate,DocumentClass.Head.date_create);
		}
	};	
	
	private OnDateSetListener OrderExecuteDateSetListener = new OnDateSetListener() {		
		@Override
		public void onDateSet(DatePicker view, int year, int month,int day) {
			
			int MinDaysToDateExecute = Integer.parseInt(MainGlobalModule.ConstantsCollection.get("MinDaysToDateExecute"));
			int MaxDaysToDateExecute = Integer.parseInt(MainGlobalModule.ConstantsCollection.get("MaxDaysToDateExecute"));
			int DaysOfWorkWeek = Integer.parseInt(MainGlobalModule.ConstantsCollection.get("DaysOfWorkWeek"));
			
			Calendar C1 = Calendar.getInstance();			
			C1.set(year, month, day);			
			
			Calendar C2 = Calendar.getInstance();
			C2.setTime(DocumentClass.Head.date_create);
			
			int DaysDiff = C1.get(Calendar.DAY_OF_YEAR)-C2.get(Calendar.DAY_OF_YEAR);
						
			if (C1.get(Calendar.YEAR) == C2.get(Calendar.YEAR) && (DaysDiff>=MinDaysToDateExecute & DaysDiff<=MaxDaysToDateExecute )) {				
				if (((C1.get(Calendar.DAY_OF_WEEK)==1?7:C1.get(Calendar.DAY_OF_WEEK)-1))>DaysOfWorkWeek) {
					Toast.makeText(Ctx, "Внимание возможно дата поставки нерабочий день !!!", Toast.LENGTH_SHORT).show();
				}			
				DocumentClass.Head.date_execute = C1.getTime();
			}
			else
			{				
				DocumentClass.SetDateExecute (); 
				Toast.makeText(Ctx, "Дата поставки вне диапазона !!!", Toast.LENGTH_SHORT).show();
			}		
			
			DocumentClass.Head.state = 1;			
			RefreshDate (OrderExecuteDate,DocumentClass.Head.date_execute);
			
		}
	};	
		
	private DialogInterface.OnClickListener OrderAccTypeDialogClickListener = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	OrderAccTypeCursor.moveToPosition(which);	    	
	    	OrderAccType.setText(OrderAccTypeCursor.getString(1));
	    	DocumentClass.Head.state = 1;
	    	DocumentClass.Head.acctype = OrderAccTypeCursor.getString(0);	    	
	  }		
	};
	
	private DialogInterface.OnClickListener OrderFirmDialogClickListener = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	OrderFirmCursor.moveToPosition(which);
	    	OrderFirm.setText(OrderFirmCursor.getString(1));
	    	DocumentClass.Head.state = 1;
	    	DocumentClass.Head.firms_id = OrderFirmCursor.getString(0);
	    }		
	  };
	 
	private DialogInterface.OnClickListener OrderDepartmentDialogClickListener = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	OrderDepartmentCursor.moveToPosition(which);	    	
	    	OrderDepartment.setText(OrderDepartmentCursor.getString(1));
	    	DocumentClass.Head.state = 1;
	    	DocumentClass.Head.departments_id = OrderDepartmentCursor.getString(0);
	  }		
	};
		
       
    public void FinishActivity () {  
    	
    	DocumentClass.Head.state = 1;
    	DocumentClass.Head.verstamp++;
    	DocumentClass.UpdateDoc();
    	DocumentClass.FinishDoc ();
    	finish();
    	
    }
       
    private void CloseDocument () {
    	
		AlertDialog.Builder builder = new AlertDialog.Builder(this);		
		builder.setTitle("Закрытие документа");
		builder.setMessage("Сохранить изменения в документе ?");
		builder.setIcon(R.drawable.ic_achtung);
		
		if ((DocumentClass.Head.total_ordersum+DocumentClass.Head.total_restsum)>0) {
			builder.setPositiveButton("Да", new DialogInterface.OnClickListener() {    				    
				public void onClick(DialogInterface dialog, int which) {
					FinishActivity ();
			        dialog.dismiss();
			    }
			});
		}		
		
		builder.setNegativeButton("Нет", new DialogInterface.OnClickListener() {
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
		    	
		    	if (DocumentClass.BackupIsExists()) {
		    		DocumentClass.RestoreDocument();
		    		finish();
		    	}
		    	else {
		    		DocumentClass.Head.customers_id = null;
		    		FinishActivity ();
		    	}		    	
		        dialog.dismiss();
		    }
		});

		builder.setNeutralButton("Отмена",new DialogInterface.OnClickListener() {			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				return;
			}
		}); 
		
		Dialog alert = builder.create();
		alert.show();    	
		
    }
    
    boolean CustomerIsSelect () {    	
    	if (DocumentClass.Head.customers_id == null ) {
    		Toast.makeText(this, "Необходимо выбрать клиента !!!",Toast.LENGTH_LONG).show();
    		return false;	
    	}    		
    	return true;
    }
     
    
    private void OpenGoodsCatalog (boolean SelectOnce) {
    	if (CustomerIsSelect()) {
    		Intent GoodsCatalog = new Intent();
    		GoodsCatalog.setClass(this,MainGoodsCatalogActivity.class);
    		GoodsCatalog.putExtra("DocType",  MainGlobalModule.DocumentsType.Order);
    		GoodsCatalog.putExtra("DocId",  DocumentClass.Head.id);
    		GoodsCatalog.putExtra("Firm",  DocumentClass.Head.firms_id);
    		GoodsCatalog.putExtra("AccType",  DocumentClass.Head.acctype);
    		GoodsCatalog.putExtra("Department",  DocumentClass.Head.departments_id);
    		GoodsCatalog.putExtra("DocSelection",  01);
    		GoodsCatalog.putExtra("SelectOnce",  SelectOnce);		
    		startActivityForResult(GoodsCatalog, IDR_GoodsSelect);
    	}
    }
    
    private void OpenDocumentsGoods () {    	
    	
    	if (CustomerIsSelect()) {    	
    		Intent OrderList = new Intent ();
    		OrderList.setClass(this,Activity_OrderList.class);    			  			
    		startActivityForResult(OrderList, IDR_OrderListOpen);
    	}
		
    }
    
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {		
		
		switch (keyCode){
		
    		case KeyEvent.KEYCODE_BACK:    			
    			return false;   			
    		
    	}	
		return super.onKeyDown(keyCode, event);
	}
	
}
